﻿using BLL;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace UI
{
    public partial class DepartmentForm : Form
    {
        private BLL.DepartmentService departmentService;
        public DepartmentForm()
        {
            departmentService = new BLL.DepartmentService();
            InitializeComponent();
        }

        private void dataTableInit()
        {
            List<Department> list = departmentService.list(new BLL.Department());
            this.department_grid_box.DataSource = list;
        }

        // 打开部门管理窗口时
        private void DepartmentForm_Load(object sender, EventArgs e)
        {
            dataTableInit();
        }

        private void employee_btn_reset_Click(object sender, EventArgs e)
        {
            this.department_name_box.Text = null;
            dataTableInit();

        }

        private void employee_name_btn_Click(object sender, EventArgs e)
        {
            // 获取参数
            Department department = new BLL.Department();
            department.DepartmentName = department_name_box.Text;
            List<Department> list = departmentService.list(department);
            this.department_grid_box.DataSource = list;
        }

        private void employee_cancel_btn_Click(object sender, EventArgs e)
        {
            this.department_panel.Visible = false;
        }

        private void add_department_btn_Click(object sender, EventArgs e)
        {
            // 清除原先残留表单数据
            this.department_name_box.Text = null;
            this.department_panel.Visible = true;
        }

        // 新增/编辑部门——确定
        private void employee_submit_btn_Click(object sender, EventArgs e)
        {


            try
            {
                // 填入表单数据
                Department department = new Department(
                    Convert.ToInt32(departmentService.getMaxId() + 1),
                    Convert.ToString(add_department_name.Text),
                    0
                    );
                // 判断同名的部门是否存在
                List<Department> list = departmentService.list(department);
                if (list.Count > 0)
                {
                    MessageBox.Show("该部门已经存在！");
                    return;
                }
                bool res = departmentService.save(department);
                if (res)
                {
                    MessageBox.Show("新增成功!");
                    // 初始化表格数据
                    dataTableInit();
                    // 关闭panel
                    department_panel.Visible = false;
                }
                else
                {
                    MessageBox.Show("新增失败!");
                }
            }
            catch (Exception)
            {
                MessageBox.Show("请填写完整表单信息!");
            }

        }
    }
}
